using Dapper;
using Finance.Api.Read.Applications.Commands.库存盘点;
using Finance.Api.Read.Dtos;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;
using System.Text;
using System.Linq;

namespace Finance.Api.Read.Applications.CommandHands.库存盘点
{
    /// <summary>
    /// 出库记录查询处理器
    /// </summary>
    public class OutRecordQueryCommandHandlers : IRequestHandler<OutRecordQueryCommand, ApiResult<List<OutRecordDto>>>
    {
        private readonly IDapperDb _db;
        private readonly ILogger<OutRecordQueryCommandHandlers> _logger;

        public OutRecordQueryCommandHandlers(IDapperDb db, ILogger<OutRecordQueryCommandHandlers> logger)
        {
            _db = db;
            _logger = logger;
        }

        public async Task<ApiResult<List<OutRecordDto>>> Handle(OutRecordQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<OutRecordDto>>();
            StringBuilder stringBuilder = new StringBuilder();

            var parameters = new DynamicParameters();
            try
            {
                // 两表联查：出库信息表、出库明细表
                stringBuilder.Append(@"SELECT 
                            ob.OutNo,
                            ob.OutTime,
                            ob.OutType,
                            ob.BoxName,
                            od.ProductNo,
                            od.ProductName,
                            ob.Message
                    FROM OutBox ob
                    INNER JOIN OutDetail od ON ob.Id = od.Outid
                    WHERE 1=1
                            AND ob.IsDelete = 0 
                            AND od.IsDelete = 0
                            AND od.checkid = @checkid");

                // 添加盘点表主键ID参数
                parameters.Add("checkid", request.checkid);

                // 添加排序
                stringBuilder.Append(" ORDER BY ob.OutTime DESC, ob.OutNo");

                // 记录SQL语句用于调试
                var sql = stringBuilder.ToString();
                _logger.LogInformation("出库记录查询SQL: {SQL}, checkid: {CheckId}", sql, request.checkid);

                // 执行数据查询
                var list = await _db.Query<OutRecordDto>(sql, parameters);
                
                result.data = list.ToList();
                result.message = $"出库记录查询成功，找到 {result.data.Count} 条记录";
                result.Code = Enumcode.ok;
            }
            catch (Exception ex)
            {
                _logger.LogError("出库记录查询失败: {Message}", ex.Message);
                result.message = "出库记录查询失败";
                result.Code = Enumcode.fail;
                throw;
            }

            return await Task.FromResult(result);
        }
    }
} 